package com.ruowei.modules.sys.web;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ruowei.common.querydsl.OptionalBooleanBuilder;
import com.ruowei.modules.foodOrder.web.dto.MerchantsDTO;
import com.ruowei.modules.sys.domain.OperateLog;
import com.ruowei.modules.sys.domain.QOperateLog;
import com.ruowei.modules.sys.domain.enumeration.OperateType;
import com.ruowei.modules.sys.pojo.dto.OperateLogDTO;
import com.ruowei.modules.sys.repository.OperateLogRepository;
import io.github.jhipster.web.util.PaginationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.time.Instant;
import java.util.List;

/**
 * REST controller for managing {@link OperateLog}.
 */
@RestController
@RequestMapping("/api")
@Transactional
@Api(tags = "操作日志")
public class OperateLogResource {

    private final Logger log = LoggerFactory.getLogger(OperateLogResource.class);
    private final QOperateLog qOperateLog = QOperateLog.operateLog;

    private final OperateLogRepository operateLogRepository;
    private final JPAQueryFactory jpaQueryFactory;

    public OperateLogResource(OperateLogRepository operateLogRepository, JPAQueryFactory jpaQueryFactory) {
        this.operateLogRepository = operateLogRepository;
        this.jpaQueryFactory = jpaQueryFactory;
    }

    @GetMapping("/operateLog")
    @ApiOperation(value = "操作日志列表")
    public ResponseEntity<List<OperateLogDTO>> operateLogList(@RequestParam(required = false) String type,
                                                              @RequestParam(required = false) String operateType,
                                                              @RequestParam(required = false) Instant startTime,
                                                              @RequestParam(required = false) Instant endTime,
                                                              Pageable pageable) {
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        if (StringUtils.isNotEmpty(type)) {
            if (type.equals("商家")) {
                booleanBuilder.and(qOperateLog.tableName.eq("Merchant"));
            } else if (type.equals("配送员")) {
                booleanBuilder.and(qOperateLog.tableName.eq("Couriers"));
            }
        }
        if (StringUtils.isNotEmpty(operateType)) {
            if (operateType.equals("新增")) {
                booleanBuilder.and(qOperateLog.operateType.eq(OperateType.CREATE));
            } else if (operateType.equals("修改")) {
                booleanBuilder.and(qOperateLog.operateType.eq(OperateType.UPDATE));
            }
        }
        OptionalBooleanBuilder predicate = new OptionalBooleanBuilder()
            .notEmptyAnd(qOperateLog.time::goe, startTime)
            .notEmptyAnd(qOperateLog.time::loe, endTime);
        booleanBuilder.and(predicate.build());
        JPAQuery<OperateLogDTO> jpaQuery = jpaQueryFactory.select(Projections.bean(OperateLogDTO.class, qOperateLog.operator, qOperateLog.operatorLogin,
            qOperateLog.code, qOperateLog.name, qOperateLog.time, qOperateLog.tableName, qOperateLog.field, qOperateLog.originalValue, qOperateLog.newValue, qOperateLog.operateType))
            .from(qOperateLog)
            .where(booleanBuilder)
            .orderBy(qOperateLog.time.desc())
            .limit(pageable.getPageSize())
            .offset(pageable.getOffset());
        Page<OperateLogDTO> page = new PageImpl<>(jpaQuery.fetch(), pageable, jpaQuery.fetchCount());
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);

        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }
}
